<?php
/**
 * Created by PhpStorm.
 * User: Short Perton
 * Date: 2016/8/30
 * Time: 10:14
 */

use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Url as UrlProvider;
use Phalcon\Mvc\View\Engine\Volt;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Mvc\Dispatcher;

$di = new FactoryDefault();

$config = include __DIR__ . '/config.php';

$di->set('config', $config);

// Setup the view component
$di->set('view', function() use($di) {
    $config = $di->get('config');
    $view = new View($config->toArray());
    $view->setViewsDir($config->application->view->viewsDir);
    $view->registerEngines(['.volt' => 'volt']);
    return $view;
});

// Setup a base URI so that all generated URIs include the "tutorial" folder
$di->set('url', function() use($config) {
    $url = new UrlProvider();
    $url->setBaseUri($config->application->baseUri);
    return $url;
});

// Setup the database service
$di->set('db', function() use($config) {
    return new DbAdapter($config->database->toArray());
});

$di->set('volt', function($view) use($config) {
    $volt = new Volt($view);
    $volt->setOptions([
        'compiledPath'      => $config->application->view->compiledPath,
        'compiledSeparator' => $config->application->view->compiledSeparator,
        'compiledExtension' => $config->application->view->compiledExtension,
        'compileAlways'     => true
    ]);
    return $volt;
});

$di->set('dispatcher', function() use($di) {
    $eventsManager = new EventsManager;
    $dispatcher = new Dispatcher();
    $dispatcher->setDefaultNamespace('sw\controller');
    $dispatcher->setEventsManager($eventsManager);
    return $dispatcher;
});